import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "抗癌卫士"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            #年龄段
            "year":[str(i) for i in range(0,56)],
            #性别
            "gender":["M","F"],
            #有无社保
            "socialSec":["Y","N"],
            #保障金额
            "money":["50000","100000","150000","200000"],
            #保障期限
            "expire":["1年"],
            #交费类型
            "payType":["年交"]
        }
        for v in product(plan["year"],plan["gender"],plan["socialSec"],plan["money"],plan["expire"],plan["payType"]):
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5]
            ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5]
            ))
    #执行爬虫
    def requestJson(self,dt=None):
        if dt["money"] == "50000":
            amount = "3"
        elif dt["money"] == "100000":
            amount = "2"
        elif dt["money"] == "150000":
            amount = "1"
        else:
            amount = "0"
        data = {
            "personAge": dt["year"],
            "gender": dt["gender"],
            "coverageAmount": amount,
            "socialSecurity": dt["socialSec"],
        }

        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.text != 0:
            price = Helper.decimalParse( r.text )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格信息失败:%d*/"%dt["id"])

    def main(self):

        while True:

            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
